<template>
  <div class="payment-page-container">
    <div class="payment-header">
      <h1>支付订单</h1>
      <div class="breadcrumb">
        <router-link to="/account" class="breadcrumb-item">我的账户</router-link>
        <i class="el-icon-arrow-right"></i>
        <router-link to="/account/recharge" class="breadcrumb-item">充值中心</router-link>
        <i class="el-icon-arrow-right"></i>
        <span class="breadcrumb-item active">支付页面</span>
      </div>
    </div>
    
    <el-card class="payment-card">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <el-alert
          :title="error"
          type="error"
          show-icon
          :closable="false"
        />
        <el-button type="primary" @click="loadPaymentInfo">重试</el-button>
      </div>
      
      <!-- 支付内容 -->
      <div v-else class="payment-content">
        <div class="payment-qr-section">
          <h3>请使用手机扫码支付</h3>
          <div class="qr-code-container">
            <img v-if="qrCodeUrl" :src="qrCodeDataUrl" alt="支付二维码" class="qr-code" />
            <div v-else class="loading-qr">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>生成支付二维码中...</span>
            </div>
          </div>
          <p class="payment-tip">请在 {{ remainingTime }} 秒内完成支付</p>
          <div class="payment-actions">
            <el-button type="primary" @click="refreshPayment" :loading="refreshing">
              刷新二维码
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
        
        <div class="payment-info-section">
          <h3>订单信息</h3>
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ rechargeNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付金额：</span>
            <span class="value amount">¥{{ paymentAmount?.toFixed(2) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">支付宝</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(new Date()) }}</span>
          </div>
          <div class="info-item">
            <span class="label">过期时间：</span>
            <span class="value">{{ formatDate(new Date(expireTime)) }}</span>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 支付结果提示 -->
    <el-dialog
      v-model="showResultDialog"
      :title="resultDialogTitle"
      :show-close="false"
      width="30%"
    >
      <div class="result-content">
        <el-icon v-if="paymentSuccess" class="success-icon"><CircleCheck /></el-icon>
        <el-icon v-else class="error-icon"><CircleClose /></el-icon>
        <p class="result-message">{{ resultDialogMessage }}</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleResultAction">
          {{ paymentSuccess ? '查看余额' : '返回重试' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Loading, CircleCheck, CircleClose } from '@element-plus/icons-vue';
import request from '@/api/request';
import type { ApiResponse } from '@/api/types';

// 路由相关
const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(true);
const error = ref<string | null>(null);
const refreshing = ref(false);
const rechargeNo = ref(route.params.rechargeNo as string);
const qrCodeUrl = ref('');
const expireTime = ref('');
const paymentAmount = ref<number | null>(null);
const remainingTime = ref(0);
const showResultDialog = ref(false);
const paymentSuccess = ref(false);
const resultDialogTitle = ref('');
const resultDialogMessage = ref('');

// 定时器
let countdownTimer: NodeJS.Timeout | null = null;
let statusCheckTimer: NodeJS.Timeout | null = null;

// 计算二维码数据URL
const qrCodeDataUrl = computed(() => {
  // 这里可以使用一个二维码生成库，或者直接使用后端提供的二维码图片URL
  // 简化版本：假设后端会返回一个可以直接在img标签中使用的URL
  return qrCodeUrl.value;
});

// 格式化日期
const formatDate = (date: Date): string => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

const loadPaymentInfo = async () => {
  loading.value = true;
  error.value = null;
  try {
    // 对于图片URL，我们需要使用完整的路径或者确保它能正确映射到后端接口
    // 由于后端接口是/api/pay，而img标签的src不会经过axios的baseURL处理
    // 所以我们需要显式添加/api前缀
    qrCodeUrl.value = `/api/pay?rechargeNo=${rechargeNo.value}`;
    
    // 而API请求会自动通过axios的baseURL添加/api前缀
    const statusResponse = await request<ApiResponse<Map<string, any>>>({
      url: '/pay/check-status',
      method: 'GET',
      params: { rechargeNo: rechargeNo.value }
    });
    
    if (statusResponse.success) {
      // 设置默认90分钟过期
      const now = new Date();
      const expireDate = new Date(now.getTime() + 90 * 60 * 1000);
      expireTime.value = expireDate.toISOString();
      
      // 从路由query参数中获取金额信息
      paymentAmount.value = Number(route.query.amount) || 0;
      
      startCountdown();
      startStatusCheck();
    } else {
      error.value = statusResponse.message || '获取支付信息失败';
    }
  } catch (err) {
    error.value = '获取支付信息失败';
    console.error('获取支付信息失败:', err);
  } finally {
    loading.value = false;
  }
};

// 修改刷新支付的方法
const refreshPayment = async () => {
  refreshing.value = true;
  try {
    // 清除现有定时器
    if (countdownTimer) {
      clearInterval(countdownTimer);
      countdownTimer = null;
    }
    if (statusCheckTimer) {
      clearInterval(statusCheckTimer);
      statusCheckTimer = null;
    }
    
    // 刷新二维码（添加时间戳避免缓存）
    const timestamp = new Date().getTime();
    qrCodeUrl.value = `/pay?rechargeNo=${rechargeNo.value}&t=${timestamp}`;
    
    // 重置过期时间为90分钟后
    const now = new Date();
    const expireDate = new Date(now.getTime() + 90 * 60 * 1000);
    expireTime.value = expireDate.toISOString();
    
    startCountdown();
    startStatusCheck();
    
    ElMessage.success('二维码已刷新');
  } catch (err) {
    ElMessage.error('刷新失败，请稍后重试');
    console.error('刷新二维码失败:', err);
  } finally {
    refreshing.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  const expireDate = new Date(expireTime.value);
  const now = new Date();
  const diff = Math.max(0, Math.floor((expireDate.getTime() - now.getTime()) / 1000));
  
  remainingTime.value = diff;
  
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  countdownTimer = setInterval(() => {
    remainingTime.value -= 1;
    if (remainingTime.value <= 0) {
      if (countdownTimer) {
        clearInterval(countdownTimer);
      }
      ElMessage.warning('二维码已过期，请刷新');
    }
  }, 1000);
};

// 开始状态检查
const startStatusCheck = () => {
  if (statusCheckTimer) {
    clearInterval(statusCheckTimer);
  }
  
  // 立即检查一次
  checkPaymentStatus();
  
  // 然后每隔3秒检查一次
  statusCheckTimer = setInterval(() => {
    checkPaymentStatus();
  }, 3000);
};

// 检查支付状态
const checkPaymentStatus = async () => {
  try {
    const response = await request<ApiResponse<{status: string, message: string}>> ({
      url: '/pay/check-status',
      method: 'GET',
      params: { rechargeNo: rechargeNo.value }
    });
    
    if (response.success && response.data) {
      if (response.data.status === 'SUCCESS' || response.data.status === 'COMPLETED') {
        // 支付成功，清除定时器并显示成功提示
        if (countdownTimer) {
          clearInterval(countdownTimer);
        }
        if (statusCheckTimer) {
          clearInterval(statusCheckTimer);
        }
        
        paymentSuccess.value = true;
        resultDialogTitle.value = '支付成功';
        resultDialogMessage.value = '您的充值已完成，余额已更新';
        showResultDialog.value = true;
      }
    }
  } catch (err) {
    console.error('检查支付状态失败:', err);
    // 静默失败，不提示用户
  }
};

// 处理结果操作
const handleResultAction = () => {
  showResultDialog.value = false;
  if (paymentSuccess.value) {
    router.push('/account');
  } else {
    loadPaymentInfo();
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 生命周期
onMounted(() => {
  if (rechargeNo.value) {
    loadPaymentInfo();
  } else {
    error.value = '未找到订单信息';
    loading.value = false;
  }
});

onUnmounted(() => {
  // 清除定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  if (statusCheckTimer) {
    clearInterval(statusCheckTimer);
  }
});
</script>

<style scoped>
.payment-page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.payment-header {
  margin-bottom: 30px;
}

.payment-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.breadcrumb-item {
  color: #606266;
  text-decoration: none;
  margin: 0 5px;
}

.breadcrumb-item:hover {
  color: #667eea;
}

.breadcrumb-item.active {
  color: #667eea;
  font-weight: 500;
}

.payment-card {
  border-radius: 12px;
  overflow: hidden;
}

.loading-container {
  padding: 40px 20px;
}

.error-container {
  padding: 40px 20px;
  text-align: center;
}

.error-container .el-button {
  margin-top: 20px;
}

.payment-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  padding: 40px;
}

.payment-qr-section {
  text-align: center;
}

.payment-qr-section h3 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 30px;
}

.qr-code-container {
  width: 300px;
  height: 300px;
  margin: 0 auto 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-code {
  width: 240px;
  height: 240px;
}

.loading-qr {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-qr span {
  margin-top: 10px;
  color: #606266;
}

.payment-tip {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.payment-info-section h3 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  font-size: 16px;
  color: #606266;
}

.info-item .value {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.info-item .value.amount {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.result-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon,
.error-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.result-message {
  font-size: 18px;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-content {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 20px;
  }
  
  .qr-code-container {
    width: 250px;
    height: 250px;
  }
  
  .qr-code {
    width: 200px;
    height: 200px;
  }
}
</style>